import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {getToken} from "@/plugins/cookie";


const routes = [
    {
        path: '/',
        name: 'Home',
        component: HomeView,
        children: [
            {
                path: '/index',
                name: 'Index',
                component:() => import('../views/IndexView.vue')
            },
            {
                path: '/course',
                name: 'Course',
                component: () => import('../views/CourseView.vue')
            },
            {
                path: '/news',
                name: 'News',
                component: () => import('../views/NewsView.vue')
            },
            {
                path: '/detail/:id',
                name: 'Detail',
                component: () => import('../views/DetailView.vue')
            },
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/LoginView.vue')
    }

]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})
router.beforeEach((to, from, next) => {
    //to,即将访问的路由对象
    //from，当前正要离开的对象
    //next.继续向后执行
    //next(false)不跳转，还在当前页面
    //next("/xxx")
    // let token = localStorage.getItem("token")
    let token = getToken()
    if (token) {
        next()
        return
    }
    if (to.name === "Login") {
        next()
        return
    }
    next({name: "Login"})

})


export default router
